package com.tencent.txcc.security;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.tencent.txcc.domain.Login;
import com.tencent.txcc.domain.Permission;
import com.tencent.txcc.service.ILoginLogService;
import com.tencent.txcc.service.ILoginService;
import com.tencent.txcc.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class LoginDetailService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login login = selectLoginByUsername(username);
        if (login != null){
            List<Permission> permissions = permissionService.selectPermissionsByLoginId(login.getId());
            if (permissions != null){
                List<SimpleGrantedAuthority> collect = permissions.stream().map(p -> new SimpleGrantedAuthority(p.getSn())
                ).collect(Collectors.toList());
                return new User(login.getUsername(),
                        login.getPassword(),
                        login.getEnabled(),
                        login.getAccountNonExpired(),
                        login.getCredentialsNonExpired(),
                        login.getAccountNonLocked(),
                        collect);
            }
        }
        return null;
    }

    private Login selectLoginByUsername(String username) {
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        return loginService.selectOne(wrapper);
    }
}
